LocalStorage and Event Delegation


Posted by wayne201299 on 2023-10-02

DEMO

點菜,將輸入的菜儲存於local storage,當網頁刷新時不會被清除

實作

  1. 監聽表單sbmit事件,將目前點的菜渲染到頁面上
     addItems.addEventListener("submit", addItem);
    
  2. 將點的菜儲存
     function addItem(e) {
         e.preventDefault();
         const text = this.querySelector("[name=item]").value;
         const item = {
             text,
             done: false,
         };
         items.push(item);
         populateList(items, itemsList);
         this.reset(); // form API
     }
    
  3. 依照菜單array內結果依序把整段菜單HTML渲染出來
     function populateList(plates = [], plateList) {
         plateList.innerHTML = plates
             .map((item, i) => {
                 return `
                 <li>
                 <input type="checkbox" data-index=${i} id="item${i}" ${
                     item.done ? "checked" : ""
                 } />
                 <label for="item${i}">${item.text}</label>
                 </li>
                 `;
             })
             .join("");
     }
    
  4. 儲存結果到local storage

    localStorage.setItem("items", JSON.stringify(items));
    
  5. 當checkbox點擊時必須要將local storage內的菜單也更新,首先監聽checkbox點擊事件

    itemsList.addEventListener("click", toggleDone);
    
  6. 實作done方法,這時會因為.plates底下有兩個element而觸發了方法兩次,需要過濾掉除了點擊checkbox外的event target,在做plateList的更新
    function toggleDone(e) {
     if (!e.target.matches("input")) return;
     const el = e.target;
     const index = el.dataset.index;
     items[index].done = !items[index].done;
     localStorage.setItem("items", JSON.stringify(items));
     populateList(items, itemsList);
    }
    

知識點

  • CSS的::before可以透過其中的content在選中的元素前插入內容
  • event.preventDefault() 是 JavaScript 中用於取消事件的默認行為的方法。它常常在處理事件時使用,以防止事件導致的預設行為發生。
  • querySelector("[name=item]")這段HTML意思是選擇property name=item的element
  • localStorage雖然很像key value的物件,但實際上他只能存字串,使用toString()的話也會找不到方法,可以透過JSON.stringify將其轉變成字串,再透過JSON.parse取得原本的物件

同場加映

localStorage、cookie 和 sessionStorage 都是在前端網頁開發中用來存儲數據的客戶端存儲解決方案,但它們有一些重要的區別:

localStorage:

localStorage 是 HTML5 引入的客戶端存儲機制。
它允許你以鍵值對的形式存儲字符串數據在瀏覽器中,並保持持久性。這意味著數據在瀏覽器被關閉後仍然存在。
存儲在 localStorage 中的數據對於相同網站的不同頁面是可見的,並且可以跨不同瀏覽器窗口和標籤共享。

cookie:

cookie 是一個小型的文本數據,由瀏覽器以鍵值對的形式存儲在客戶端。
cookie 有一些限制,例如每個 cookie 的大小通常有限制,並且瀏覽器每次向同一網站發送 HTTP 請求時都會將 cookie 附加到請求頭中。
cookie 可以設置過期時間,並且可以在伺服器端進行訪問和修改。

sessionStorage:

sessionStorage 與 localStorage 類似,但它的生命週期限制在瀏覽器窗口或標籤的生命週期內。當窗口或標籤被關閉時,sessionStorage 中的數據將被刪除。
存儲在 sessionStorage 中的數據對於相同瀏覽器窗口或標籤中的不同頁面是可見的。
選擇哪個存儲機制取決於你的需求:

如果你需要在瀏覽器會話期間(窗口或標籤的生命週期)內存儲數據,可以使用 sessionStorage。
如果你需要持久性存儲並且希望數據在不同瀏覽器窗口和標籤之間共享,可以使用 localStorage。
如果你只需要在伺服器端訪問數據,可以使用 cookie,但要注意 cookie 有一些限制。


#javascript #css #html







Related Posts

1731. The Number of Employees Which Report to Each Employee

1731. The Number of Employees Which Report to Each Employee

初探 DNS 系統

初探 DNS 系統

Module build failed (from ./node_modules/sass-loader/dist/cjs.js)

Module build failed (from ./node_modules/sass-loader/dist/cjs.js)


Comments